package com.loser.excel.core.handler.upload;

import cn.hutool.core.date.DateUtil;
import com.loser.excel.aspect.ExcelExportAspect;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * 保存文件的服务类
 */
public class DefaultUploadFileHandler implements UploadFileHandler {

    private static final Logger log = LogManager.getLogger(ExcelExportAspect.class);

    @Override
    public String uploadWordBook2cos(SXSSFWorkbook wb, String fileName, String path, String categoryType, String optUser) {

        try {
            path = path + getTimeDir() + optUser + "/";
            if (StringUtils.isNotEmpty(categoryType)) {
                path = path + categoryType + "/";
            }
            File file = new File(path);
            // 如果文件夹不存在则创建
            if (!file.exists() && !file.isDirectory()) {
                // 创建多级目录
                file.mkdirs();
            }
            String filePath = path + fileName;
            FileOutputStream fout = new FileOutputStream(filePath);
            wb.write(fout);
            fout.close();
        } catch (Exception e) {
            log.error("uploadWordBook2cos catch throw a e", e);
            e.printStackTrace();
        } finally {
            try {
                if (Objects.nonNull(wb)) {
                    wb.dispose();
                    wb.close();
                }
            } catch (IOException e) {
                log.error("uploadWordBook2cos finally throw a e", e);
                e.printStackTrace();
            }
        }
        return path + fileName;
    }

    private String getTimeDir() {
        return DateUtil.format(new Date(), "yyyy/MM/dd/");
    }

}
